/**
 * 蓝牙Modbus通信工具类
 * 用于处理蓝牙连接和Modbus协议通信
 * 支持低功耗蓝牙(BLE)通信
 */
// 蓝牙连接状态
const BLUETOOTH_STATE = {
	DISCONNECTED: 0, // 未连接
	CONNECTING: 1, // 连接中
	CONNECTED: 2, // 已连接
	SERVICES_DISCOVERING: 3, // 正在读取服务
	RECONNECTING: 4, // 正在重连
};

// Modbus功能码
const MODBUS_FUNCTION_CODE = {
	READ_COILS: 0x01, // 读线圈
	READ_DISCRETE_INPUTS: 0x02, // 读离散输入
	READ_HOLDING_REGISTERS: 0x03, // 读保持寄存器
	READ_INPUT_REGISTERS: 0x04, // 读输入寄存器
	WRITE_SINGLE_COIL: 0x05, // 写单个线圈
	WRITE_SINGLE_REGISTER: 0x06, // 写单个寄存器
	WRITE_MULTIPLE_COILS: 0x0f, // 写多个线圈
	WRITE_MULTIPLE_REGISTERS: 0x10, // 写多个寄存器
};

// 预设的蓝牙模块类型
const BLUETOOTH_MODULE_TYPE = {
	NORMAL: "normal", // 常规模组
	BT16: "bt16", // BT16模组
	CUSTOM: "custom", // 自定义UUID
	BLE: "ble", // 低功耗蓝牙模式
};

// 常规模组的UUID
const NORMAL_MODULE_UUID = {
	serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
	writeId: "0000FFE1-0000-1000-8000-00805F9B34FB",
	notifyId: "0000FFE1-0000-1000-8000-00805F9B34FB",
};

// BT16模组的UUID
const BT16_MODULE_UUID = {
	serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
	writeId: "0000FFE2-0000-1000-8000-00805F9B34FB",
	notifyId: "0000FFE1-0000-1000-8000-00805F9B34FB",
};

// 低功耗蓝牙通用UUID
const BLE_MODULE_UUID = {
	// 通用串口服务
	serviceId: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E",
	// 写特征值
	writeId: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E",
	// 通知特征值
	notifyId: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E",
};

class BluetoothModbus {
	constructor() {
		this.state = BLUETOOTH_STATE.DISCONNECTED;
		this.deviceId = "";
		this.deviceName = "";
		this.serviceId = "";
		this.writeId = "";
		this.notifyId = "";
		this.moduleType = BLUETOOTH_MODULE_TYPE.NORMAL;
		this.customUUID = null;
		this.isInitialized = false;
		this.devicesList = [];
		this.onStateChangeCallback = null;
		this.onDataReceivedCallback = null;
		this.onDeviceFoundCallback = null;
		this.onErrorCallback = null;

		// 获取服务重试相关属性
		this.serviceRetryCount = 0;
		this.maxServiceRetryAttempts = 10;
		this.serviceRetryDelay = 2000; // 2秒

		// 心跳保活相关属性
		this.heartbeatInterval = null; // 心跳定时器
		this.heartbeatPeriod = 30000; // 心跳周期，默认5秒
		this.heartbeatData = new Uint8Array([0x00]); // 心跳数据包
		this.autoReconnect = true; // 是否自动重连
		this.reconnectCount = 0; // 重连计数
		this.maxReconnectAttempts = 10; // 最大重连次数
		this.reconnectDelay = 3000; // 重连延迟，默认3秒
	}

	/**
	 * 初始化蓝牙模块
	 * @returns {Promise} 初始化结果
	 */
	async init() {
		if (this.isInitialized) {
			return Promise.resolve(true);
		}
		return new Promise((resolve, reject) => {
			uni.openBluetoothAdapter({
				success: (res) => {
					uni.getBluetoothAdapterState({
						success: res => {
							console.log('获取本机蓝牙适配器状态', JSON.stringify(res));

							this._startBluetoothDevicesDiscovery();
							this._listenBluetoothAdapterStateChange();
							this._listenBluetoothDeviceFound();
							this._listenBLEConnectionStateChange();
							this._listenBLECharacteristicValueChange();
						},
						fail: e => {
							console.error("获取本机蓝牙适配器状态异常", e);

						}
					});
					console.log("蓝牙初始化成功", res);
					this.isInitialized = true;

					resolve(true);
				},
				fail: (err) => {
					uni.showToast({
						title: '蓝牙初始化失败，请检查设备是否支持蓝牙或蓝牙是否开启',
						icon: 'none'
					})
					console.error("蓝牙初始化失败", err);
					this._handleError(
						"蓝牙初始化失败，请检查设备是否支持蓝牙或蓝牙是否开启",
						err
					);
					reject(err);
				},
			});
		});
	}

	/**
	 * 设置蓝牙模块类型
	 * @param {string} type 模块类型
	 * @param {Object} customUUID 自定义UUID（当type为custom时必填）
	 */
	setModuleType(type, customUUID = null) {
		this.moduleType = type;

		switch (type) {
			case BLUETOOTH_MODULE_TYPE.NORMAL:
				this.serviceId = NORMAL_MODULE_UUID.serviceId;
				this.writeId = NORMAL_MODULE_UUID.writeId;
				this.notifyId = NORMAL_MODULE_UUID.notifyId;
				break;
			case BLUETOOTH_MODULE_TYPE.BT16:
				this.serviceId = BT16_MODULE_UUID.serviceId;
				this.writeId = BT16_MODULE_UUID.writeId;
				this.notifyId = BT16_MODULE_UUID.notifyId;
				break;
			case BLUETOOTH_MODULE_TYPE.BLE:
				this.serviceId = BLE_MODULE_UUID.serviceId;
				this.writeId = BLE_MODULE_UUID.writeId;
				this.notifyId = BLE_MODULE_UUID.notifyId;
				break;
			case BLUETOOTH_MODULE_TYPE.CUSTOM:
				if (
					!customUUID ||
					!customUUID.serviceId ||
					!customUUID.writeId ||
					!customUUID.notifyId
				) {
					this._handleError("自定义UUID参数不完整", {
						customUUID
					});
					return;
				}
				this.serviceId = customUUID.serviceId;
				this.writeId = customUUID.writeId;
				this.notifyId = customUUID.notifyId;
				this.customUUID = customUUID;
				break;
			default:
				this._handleError("不支持的模块类型", {
					type
				});
		}
	}

	/**
	 * 设置心跳保活参数
	 * @param {Uint8Array} heartbeatData 心跳数据包
	 * @param {number} heartbeatPeriod 心跳周期（毫秒）
	 * @param {boolean} autoReconnect 是否自动重连
	 * @param {number} maxReconnectAttempts 最大重连次数
	 * @param {number} reconnectDelay 重连延迟（毫秒）
	 */
	setHeartbeatOptions(
		heartbeatData = null,
		heartbeatPeriod = 5000,
		autoReconnect = true,
		maxReconnectAttempts = 5,
		reconnectDelay = 3000
	) {
		if (heartbeatData) {
			this.heartbeatData = heartbeatData;
		}
		this.heartbeatPeriod = heartbeatPeriod;
		this.autoReconnect = autoReconnect;
		this.maxReconnectAttempts = maxReconnectAttempts;
		this.reconnectDelay = reconnectDelay;
	}

	/**
	 * 开始搜索蓝牙设备
	 * @returns {Promise} 搜索结果
	 */
	startScan() {
		this.devicesList = [];
		if (!this.isInitialized) {
			return this.init().then(() => this._startBluetoothDevicesDiscovery());
		}
		return this._startBluetoothDevicesDiscovery();
	}

	/**
	 * 停止搜索蓝牙设备
	 */
	stopScan() {
		uni.stopBluetoothDevicesDiscovery({
			success: (res) => {
				console.log("serviceId---", this.serviceId);
				console.log("停止搜索蓝牙设备成功", res);
			},
			fail: (err) => {
				console.error("停止搜索蓝牙设备失败", err);
			},
		});
	}

	/**
	 * 连接蓝牙设备
	 * @param {string} deviceId 设备ID
	 * @param {string} deviceName 设备名称
	 * @returns {Promise} 连接结果
	 */
	async connect(deviceId, deviceName) {
		if (!this.isInitialized) {
			await this.init();
		}

		// 如果是重连状态，检查重连次数
		if (this.state === BLUETOOTH_STATE.RECONNECTING) {
			// 注意：重连计数在失败回调中增加，这里只检查是否超过最大次数
			if (this.reconnectCount >= this.maxReconnectAttempts) {
				this.state = BLUETOOTH_STATE.DISCONNECTED;
				this._notifyStateChange();
				return Promise.reject(
					new Error(`重连失败，已达到最大重连次数 ${this.maxReconnectAttempts}`)
				);
			}
			console.log(`正在尝试第${this.reconnectCount + 1}次重连...`);
		} else {
			this.deviceId = deviceId;
			this.deviceName = deviceName;
			this.state = BLUETOOTH_STATE.CONNECTING;
			this._notifyStateChange();
		}

		return new Promise((resolve, reject) => {
			// 先停止搜索
			this.stopScan();

			// 连接设备
			uni.createBLEConnection({
				deviceId: deviceId,
				timeout: 20000, // 10秒超时
				success: (res) => {
					console.log("连接蓝牙设备成功", res);
					// 连接成功后，状态变为正在读取服务
					this.state = BLUETOOTH_STATE.SERVICES_DISCOVERING;
					this._notifyStateChange();

					uni.getConnectedBluetoothDevices({
						success: (res) => {
							console.log("获取已连接设备成功", res);
							// 重置服务重试计数
							this.serviceRetryCount = 0;
							setTimeout(() => {
								// 获取设备服务，添加重试机制
								this._getBLEDeviceServicesWithRetry(
										deviceId)
									.then(() => {
										// 服务读取成功后，状态变为已连接
										this.state = BLUETOOTH_STATE
											.CONNECTED;
										this._notifyStateChange();
										// 启动心跳保活
										this._startHeartbeat();
										resolve(true);
									})
									.catch((err) => {
										this._handleError(
											"获取蓝牙服务失败，已达到最大重试次数",
											err
										);
										this.disconnect();
										reject(err);
									});
							}, this.serviceRetryDelay);
						},
						fail: (err) => {
							console.error("获取已连接设备失败", err);
						},
					});
				},
				fail: (err) => {
					console.error("连接蓝牙设备失败", err);
					// 如果是重连状态且失败，尝试再次重连
					if (this.state === BLUETOOTH_STATE.RECONNECTING) {
						this.reconnectCount++;
						if (this.reconnectCount < this.maxReconnectAttempts) {
							console.log(
								`重连失败，${this.reconnectDelay}ms后尝试第${
                  this.reconnectCount + 1
                }次重连...`
							);
							setTimeout(
								() => this.connect(deviceId, deviceName),
								this.reconnectDelay
							);
							return;
						} else {
							console.log(
								`重连失败，已达到最大重连次数${this.maxReconnectAttempts}`
							);
							uni.showModal({
								title: "提示",
								content: `重连失败，请检查设备是否连接正常; 也可重新开启蓝牙进行搜索设备进行重连！`,
								success: function(res) {
									if (res.confirm) {
										console.log("用户点击确定");
									} else if (res.cancel) {
										console.log("用户点击取消");
									}
								},
							});
						}
					}

					this._handleError("连接蓝牙设备失败", err);
					this.state = BLUETOOTH_STATE.DISCONNECTED;
					this._notifyStateChange();
					reject(err);
				},
			});
		});
	}

	/**
	 * 断开蓝牙连接
	 */
	disconnect() {
		if (this.state === BLUETOOTH_STATE.DISCONNECTED || !this.deviceId) {
			return;
		}

		// 停止心跳
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval);
			this.heartbeatInterval = null;
		}

		// 重置服务重试计数和重连计数
		this.serviceRetryCount = 0;
		this.reconnectCount = 0;

		uni.closeBLEConnection({
			deviceId: this.deviceId,
			success: (res) => {
				console.log("断开蓝牙连接成功", res);
				this.state = BLUETOOTH_STATE.DISCONNECTED;
				this._notifyStateChange();
			},
			fail: (err) => {
				console.error("断开蓝牙连接失败", err);
			},
		});
	}

	/**
	 * 关闭蓝牙模块
	 */
	close() {
		this.disconnect();
		uni.closeBluetoothAdapter({
			success: (res) => {
				console.log("关闭蓝牙模块成功", res);
				this.isInitialized = false;
			},
			fail: (err) => {
				console.error("关闭蓝牙模块失败", err);
			},
		});
	}

	/**
	 * 发送Modbus请求
	 * @param {number} slaveId 从站地址
	 * @param {number} functionCode 功能码
	 * @param {number} startAddress 起始地址
	 * @param {number|Array} value 值或值数组
	 * @returns {Promise} 发送结果
	 */
	sendModbusRequest(slaveId, functionCode, startAddress, value) {
		if (this.state !== BLUETOOTH_STATE.CONNECTED) {
			return Promise.reject(new Error("蓝牙未连接"));
		}

		let pdu = null;

		switch (functionCode) {
			case MODBUS_FUNCTION_CODE.READ_COILS:
			case MODBUS_FUNCTION_CODE.READ_DISCRETE_INPUTS:
			case MODBUS_FUNCTION_CODE.READ_HOLDING_REGISTERS:
			case MODBUS_FUNCTION_CODE.READ_INPUT_REGISTERS:
				pdu = this._createReadPDU(functionCode, startAddress, value); // value为要读取的数量
				break;
			case MODBUS_FUNCTION_CODE.WRITE_SINGLE_COIL:
				pdu = this._createWriteSingleCoilPDU(startAddress, value);
				break;
			case MODBUS_FUNCTION_CODE.WRITE_SINGLE_REGISTER:
				pdu = this._createWriteSingleRegisterPDU(startAddress, value);
				break;
			case MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_COILS:
				pdu = this._createWriteMultipleCoilsPDU(startAddress, value);
				break;
			case MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_REGISTERS:
				pdu = this._createWriteMultipleRegistersPDU(startAddress, value);
				break;
			default:
				return Promise.reject(new Error("不支持的功能码"));
		}

		// 添加从站地址
		const adu = new Uint8Array(pdu.length + 1);
		adu[0] = slaveId;
		adu.set(pdu, 1);

		// 计算CRC校验
		const crc = this._calculateCRC16(adu);
		const buffer = new Uint8Array(adu.length + 2);
		buffer.set(adu);
		buffer[adu.length] = crc & 0xff; // CRC低字节
		buffer[adu.length + 1] = (crc >> 8) & 0xff; // CRC高字节

		return this._sendData(buffer);
	}

	/**
	 * 解析Modbus响应
	 * @param {ArrayBuffer} data 接收到的数据
	 * @returns {Object} 解析结果
	 */
	parseModbusResponse(data) {
		const buffer = new Uint8Array(data);

		// 检查数据长度
		if (buffer.length < 5) {
			// 至少需要从站地址(1) + 功能码(1) + 数据(1) + CRC(2)
			return {
				error: "数据长度不足"
			};
		}

		// 提取数据
		const slaveId = buffer[0];
		const functionCode = buffer[1];

		// 检查是否为错误响应
		if (functionCode & 0x80) {
			const errorCode = buffer[2];
			return {
				slaveId,
				functionCode: functionCode & 0x7f,
				error: true,
				errorCode,
			};
		}

		// 根据功能码解析数据
		switch (functionCode) {
			case MODBUS_FUNCTION_CODE.READ_COILS:
			case MODBUS_FUNCTION_CODE.READ_DISCRETE_INPUTS:
				return this._parseReadBitsResponse(buffer);
			case MODBUS_FUNCTION_CODE.READ_HOLDING_REGISTERS:
			case MODBUS_FUNCTION_CODE.READ_INPUT_REGISTERS:
				return this._parseReadRegistersResponse(buffer);
			case MODBUS_FUNCTION_CODE.WRITE_SINGLE_COIL:
				return this._parseWriteSingleCoilResponse(buffer);
			case MODBUS_FUNCTION_CODE.WRITE_SINGLE_REGISTER:
				return this._parseWriteSingleRegisterResponse(buffer);
			case MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_COILS:
			case MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_REGISTERS:
				return this._parseWriteMultipleResponse(buffer);
			default:
				return {
					error: "不支持的功能码"
				};
		}
	}

	/**
	 * 设置状态变化回调
	 * @param {Function} callback 回调函数
	 */
	onStateChange(callback) {
		this.onStateChangeCallback = callback;
	}

	/**
	 * 设置数据接收回调
	 * @param {Function} callback 回调函数
	 */
	onDataReceived(callback) {
		this.onDataReceivedCallback = callback;
	}

	/**
	 * 设置设备发现回调
	 * @param {Function} callback 回调函数
	 */
	onDeviceFound(callback) {
		this.onDeviceFoundCallback = callback;
	}

	/**
	 * 设置错误回调
	 * @param {Function} callback 回调函数
	 */
	onError(callback) {
		this.onErrorCallback = callback;
	}

	/**
	 * 获取当前连接状态
	 * @returns {number} 连接状态
	 */
	getState() {
		return this.state;
	}

	/**
	 * 获取已发现的设备列表
	 * @returns {Array} 设备列表
	 */
	getDevicesList() {
		return this.devicesList;
	}

	/**
	 * 获取当前连接的设备信息
	 * @returns {Object} 设备信息
	 */
	getConnectedDeviceInfo() {
		if (this.state !== BLUETOOTH_STATE.CONNECTED) {
			return null;
		}
		return {
			deviceId: this.deviceId,
			deviceName: this.deviceName,
			serviceId: this.serviceId,
			writeId: this.writeId,
			notifyId: this.notifyId,
		};
	}

	// 私有方法

	/**
	 * 开始搜索蓝牙设备
	 * @returns {Promise} 搜索结果
	 */
	_startBluetoothDevicesDiscovery() {
		console.log('-----kaishisousuo')
		return new Promise((resolve, reject) => {
			// 配置搜索参数
			const options = {
				allowDuplicatesKey: false,
				powerLevel: "high",
				// 启用搜索BLE设备
				interval: 0, // 0表示使用系统默认的搜索间隔
			};
			console.log('this.serviceId--------', this.serviceId)
			// 如果是BLE模式，添加服务UUID过滤
			if (this.moduleType === BLUETOOTH_MODULE_TYPE.BLE) {
				options.services = [this.serviceId];
			}
			uni.startBluetoothDevicesDiscovery({
				...options,
				success: (res) => {
					console.log("开始搜索蓝牙设备成功", res);
					resolve(res);
				},
				fail: (err) => {
					console.error("开始搜索蓝牙设备失败", err);
					this._handleError("开始搜索蓝牙设备失败", err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 监听蓝牙适配器状态变化
	 */
	_listenBluetoothAdapterStateChange() {
		uni.onBluetoothAdapterStateChange((res) => {
			console.log("蓝牙适配器状态变化", res);
			if (!res.available) {
				this.isInitialized = false;
				this.state = BLUETOOTH_STATE.DISCONNECTED;
				this._notifyStateChange();
				this._handleError("蓝牙适配器不可用", res);
			}
		});
	}

	/**
	 * 监听发现新设备
	 */
	_listenBluetoothDeviceFound() {
		uni.onBluetoothDeviceFound((res) => {
			console.log("发现蓝牙设备", res.devices);
			if (this.state === BLUETOOTH_STATE.CONNECTED) {
				this.stopScan();
			}
			console.log(this.state, BLUETOOTH_STATE.CONNECTED);
			if (!res.devices || res.devices.length === 0) {
				return;
			}

			res.devices.forEach((device) => {
				// 低功耗蓝牙模式下，即使没有名称也添加设备
				if (
					this.moduleType !== BLUETOOTH_MODULE_TYPE.BLE &&
					!device.name &&
					!device.localName
				) {
					return;
				}

				// 检查设备是否支持BLE
				const isBLEDevice =
					device.advertisData ||
					device.advertisServiceUUIDs ||
					(device.serviceData && Object.keys(device.serviceData).length > 0);

				// 如果是BLE模式但设备不支持BLE，则跳过
				// if (this.moduleType === BLUETOOTH_MODULE_TYPE.BLE && !isBLEDevice) {
				//   return
				// }

				// 检查是否已存在该设备
				const index = this.devicesList.findIndex(
					(item) => item.deviceId === device.deviceId
				);
				if (index !== -1) {
					// 更新设备信息
					this.devicesList[index] = device;
				} else {
					// 添加新设备
					this.devicesList.push(device);
				}
			});

			// 通知设备发现回调
			if (this.onDeviceFoundCallback) {
				this.onDeviceFoundCallback(this.devicesList);
			}
			console.log(this.devicesList);
		});
	}

	/**
	 * 监听蓝牙连接状态变化
	 */
	_listenBLEConnectionStateChange() {
		uni.onBLEConnectionStateChange((res) => {
			console.log("蓝牙连接状态变化", res);

			// 如果设备断开连接
			if (!res.connected && this.deviceId === res.deviceId) {
				// 停止心跳
				this._stopHeartbeat();

				// 如果不是主动断开连接（状态不是DISCONNECTED），则尝试自动重连
				if (this.state !== BLUETOOTH_STATE.DISCONNECTED && this.autoReconnect) {
					console.log(
						`检测到连接断开，将在${this.reconnectDelay}ms后尝试自动重连...`
					);
					this.state = BLUETOOTH_STATE.RECONNECTING;
					this._notifyStateChange();
					this.reconnectCount = 0;
					setTimeout(
						() => this.connect(this.deviceId, this.deviceName),
						this.reconnectDelay
					);
					return;
				} else if (
					this.state !== BLUETOOTH_STATE.DISCONNECTED &&
					!this.autoReconnect
				) {
					console.log("检测到连接断开，但自动重连已禁用");
				}

				this.state = BLUETOOTH_STATE.DISCONNECTED;
				this._notifyStateChange();
			}
		});
	}

	/**
	 * 监听特征值变化
	 */
	_listenBLECharacteristicValueChange() {
		uni.onBLECharacteristicValueChange((res) => {
			if (this.onDataReceivedCallback) {
				this.onDataReceivedCallback(res.value);
			}
		});
	}

	/**
	 * 获取蓝牙设备服务
	 * @param {string} deviceId 设备ID
	 * @returns {Promise} 获取结果
	 */
	/**
	 * 获取蓝牙设备服务（带重试机制）
	 * @param {string} deviceId 设备ID
	 * @returns {Promise} 获取结果
	 */
	_getBLEDeviceServicesWithRetry(deviceId) {
		return new Promise((resolve, reject) => {
			// 尝试获取服务
			this._tryGetBLEDeviceServices(deviceId, resolve, reject);
		});
	}

	/**
	 * 尝试获取蓝牙设备服务，失败后重试
	 * @param {string} deviceId 设备ID
	 * @param {Function} resolve Promise解析函数
	 * @param {Function} reject Promise拒绝函数
	 */
	_tryGetBLEDeviceServices(deviceId, resolve, reject) {
		console.log(`尝试获取蓝牙设备服务，第${this.serviceRetryCount + 1}次尝试`);

		this._getBLEDeviceServices(deviceId)
			.then(resolve)
			.catch((err) => {
				this.serviceRetryCount++;
				console.log(
					`获取蓝牙设备服务失败，当前重试次数：${this.serviceRetryCount}`
				);

				if (this.serviceRetryCount < this.maxServiceRetryAttempts) {
					console.log(`将在${this.serviceRetryDelay / 1000}秒后重试获取服务`);
					// 通知UI当前重试次数
					this._notifyStateChange({
						serviceRetryCount: this.serviceRetryCount,
						maxServiceRetryAttempts: this.maxServiceRetryAttempts,
					});
					// 延时后重试
					setTimeout(() => {
						this._tryGetBLEDeviceServices(deviceId, resolve, reject);
					}, this.serviceRetryDelay);
				} else {
					// 达到最大重试次数，重置计数并拒绝Promise
					console.error(
						`获取蓝牙设备服务失败，已达到最大重试次数${this.maxServiceRetryAttempts}`
					);
					this.serviceRetryCount = 0;
					reject(err);
				}
			});
	}

	_getBLEDeviceServices(deviceId) {
		return new Promise((resolve, reject) => {
			uni.getBLEDeviceServices({
				deviceId: deviceId,
				success: (res) => {
					console.log("获取蓝牙设备服务成功", res);

					// 查找指定服务
					// const service = res.services.find(
					//   (s) => s.uuid.toUpperCase() === this.serviceId.toUpperCase()
					// );
					// 查找指定服务
					const service = res.services.find(
						(s) =>
						s.uuid.toUpperCase() === this.serviceId.toUpperCase() ||
						s.uuid.toLowerCase() === this.serviceId.toLowerCase() ||
						s.uuid.replace(/-/g, "") === this.serviceId.replace(/-/g, "")
					);
					// 获取特征值
					console.log(
						"开始获取特征值-----------------------------------------",
						this.serviceId,
						service
					);
					if (!service) {
						reject(new Error("未找到指定服务"));
						return;
					}

					this._getBLEDeviceCharacteristics(deviceId, service.uuid)
						.then(resolve)
						.catch(reject);
				},
				fail: (err) => {
					console.error("获取蓝牙设备服务失败", err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 获取蓝牙设备特征值
	 * @param {string} deviceId 设备ID
	 * @param {string} serviceId 服务ID
	 * @returns {Promise} 获取结果
	 */
	_getBLEDeviceCharacteristics(deviceId, serviceId) {
		return new Promise((resolve, reject) => {
			uni.getBLEDeviceCharacteristics({
				deviceId: deviceId,
				serviceId: serviceId,
				success: (res) => {
					console.log("获取蓝牙设备特征值成功", res);

					// 查找写特征值
					const writeCharacteristic = res.characteristics.find(
						(c) =>
						c.uuid.toUpperCase() === this.writeId.toUpperCase() &&
						c.properties.write
					);

					// 查找通知特征值
					const notifyCharacteristic = res.characteristics.find(
						(c) =>
						c.uuid.toUpperCase() === this.notifyId.toUpperCase() &&
						c.properties.notify
					);

					if (!writeCharacteristic) {
						reject(new Error("未找到可写特征值"));
						return;
					}

					if (!notifyCharacteristic) {
						reject(new Error("未找到可通知特征值"));
						return;
					}

					// 启用通知
					this._notifyBLECharacteristicValueChange(
							deviceId,
							serviceId,
							this.notifyId
						)
						.then(resolve)
						.catch(reject);
				},
				fail: (err) => {
					console.error("获取蓝牙设备特征值失败", err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 启用特征值变化通知
	 * @param {string} deviceId 设备ID
	 * @param {string} serviceId 服务ID
	 * @param {string} characteristicId 特征值ID
	 * @returns {Promise} 启用结果
	 */
	_notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
		return new Promise((resolve, reject) => {
			uni.notifyBLECharacteristicValueChange({
				deviceId: deviceId,
				serviceId: serviceId,
				characteristicId: characteristicId,
				state: true,
				success: (res) => {
					console.log("启用特征值变化通知成功", res);
					resolve(res);
				},
				fail: (err) => {
					console.error("启用特征值变化通知失败", err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 发送数据
	 * @param {ArrayBuffer|Uint8Array} data 要发送的数据
	 * @returns {Promise} 发送结果
	 */
	_sendData(data) {
		if (this.state !== BLUETOOTH_STATE.CONNECTED) {
			return Promise.reject(new Error("蓝牙未连接"));
		}

		// 确保数据是ArrayBuffer类型
		let buffer = data;
		if (data instanceof Uint8Array) {
			buffer = data.buffer;
		}

		// 低功耗蓝牙模式下，考虑MTU限制，默认MTU为20字节
		if (
			this.moduleType === BLUETOOTH_MODULE_TYPE.BLE &&
			buffer.byteLength > 20
		) {
			return this._sendLargeData(buffer);
		}

		return new Promise((resolve, reject) => {
			uni.writeBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId: this.writeId,
				value: buffer,
				success: (res) => {
					console.log("发送数据成功", res);
					resolve(res);
				},
				fail: (err) => {
					console.error("发送数据失败", err);
					this._handleError("发送数据失败", err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 分片发送大数据
	 * @param {ArrayBuffer} buffer 要发送的数据
	 * @returns {Promise} 发送结果
	 */
	_sendLargeData(buffer) {
		return new Promise(async (resolve, reject) => {
			try {
				const data = new Uint8Array(buffer);
				const chunkSize = 20; // 默认MTU大小
				const chunks = Math.ceil(data.length / chunkSize);

				console.log(`数据大小: ${data.length}字节, 分为${chunks}个分片发送`);

				for (let i = 0; i < chunks; i++) {
					const start = i * chunkSize;
					const end = Math.min(start + chunkSize, data.length);
					const chunk = data.slice(start, end);

					// 发送分片
					await new Promise((chunkResolve, chunkReject) => {
						uni.writeBLECharacteristicValue({
							deviceId: this.deviceId,
							serviceId: this.serviceId,
							characteristicId: this.writeId,
							value: chunk.buffer,
							success: (res) => {
								console.log(`分片${i + 1}/${chunks}发送成功`);
								chunkResolve(res);
							},
							fail: (err) => {
								console.error(`分片${i + 1}/${chunks}发送失败`, err);
								chunkReject(err);
							},
						});
					});

					// 每个分片之间添加延迟，避免发送过快导致丢包
					if (i < chunks - 1) {
						await new Promise((r) => setTimeout(r, 20));
					}
				}

				resolve({
					errMsg: "writeBLECharacteristicValue:ok"
				});
			} catch (err) {
				console.error("分片发送失败", err);
				this._handleError("分片发送失败", err);
				reject(err);
			}
		});
	}

	/**
	 * 创建读取PDU
	 * @param {number} functionCode 功能码
	 * @param {number} address 地址
	 * @param {number} quantity 数量
	 * @returns {Uint8Array} PDU
	 */
	_createReadPDU(functionCode, address, quantity) {
		const pdu = new Uint8Array(5);
		pdu[0] = functionCode;
		pdu[1] = (address >> 8) & 0xff; // 地址高字节
		pdu[2] = address & 0xff; // 地址低字节
		pdu[3] = (quantity >> 8) & 0xff; // 数量高字节
		pdu[4] = quantity & 0xff; // 数量低字节
		return pdu;
	}

	/**
	 * 创建写单个线圈PDU
	 * @param {number} address 地址
	 * @param {boolean} value 值
	 * @returns {Uint8Array} PDU
	 */
	_createWriteSingleCoilPDU(address, value) {
		const pdu = new Uint8Array(5);
		pdu[0] = MODBUS_FUNCTION_CODE.WRITE_SINGLE_COIL;
		pdu[1] = (address >> 8) & 0xff; // 地址高字节
		pdu[2] = address & 0xff; // 地址低字节
		pdu[3] = value ? 0xff : 0x00; // 值高字节 (ON=0xFF00, OFF=0x0000)
		pdu[4] = 0x00; // 值低字节
		return pdu;
	}

	/**
	 * 创建写单个寄存器PDU
	 * @param {number} address 地址
	 * @param {number} value 值
	 * @returns {Uint8Array} PDU
	 */
	_createWriteSingleRegisterPDU(address, value) {
		const pdu = new Uint8Array(5);
		pdu[0] = MODBUS_FUNCTION_CODE.WRITE_SINGLE_REGISTER;
		pdu[1] = (address >> 8) & 0xff; // 地址高字节
		pdu[2] = address & 0xff; // 地址低字节
		pdu[3] = (value >> 8) & 0xff; // 值高字节
		pdu[4] = value & 0xff; // 值低字节
		return pdu;
	}

	/**
	 * 创建写多个线圈PDU
	 * @param {number} address 地址
	 * @param {Array<boolean>} values 值数组
	 * @returns {Uint8Array} PDU
	 */
	_createWriteMultipleCoilsPDU(address, values) {
		const quantity = values.length;
		const byteCount = Math.ceil(quantity / 8);

		const pdu = new Uint8Array(6 + byteCount);
		pdu[0] = MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_COILS;
		pdu[1] = (address >> 8) & 0xff; // 地址高字节
		pdu[2] = address & 0xff; // 地址低字节
		pdu[3] = (quantity >> 8) & 0xff; // 数量高字节
		pdu[4] = quantity & 0xff; // 数量低字节
		pdu[5] = byteCount; // 字节数

		// 填充数据
		for (let i = 0; i < byteCount; i++) {
			let byte = 0;
			for (let j = 0; j < 8; j++) {
				const index = i * 8 + j;
				if (index < quantity && values[index]) {
					byte |= 1 << j;
				}
			}
			pdu[6 + i] = byte;
		}

		return pdu;
	}

	/**
	 * 创建写多个寄存器PDU
	 * @param {number} address 地址
	 * @param {Array<number>} values 值数组
	 * @returns {Uint8Array} PDU
	 */
	_createWriteMultipleRegistersPDU(address, values) {
		const quantity = values.length;
		const byteCount = quantity * 2;

		const pdu = new Uint8Array(6 + byteCount);
		pdu[0] = MODBUS_FUNCTION_CODE.WRITE_MULTIPLE_REGISTERS;
		pdu[1] = (address >> 8) & 0xff; // 地址高字节
		pdu[2] = address & 0xff; // 地址低字节
		pdu[3] = (quantity >> 8) & 0xff; // 数量高字节
		pdu[4] = quantity & 0xff; // 数量低字节
		pdu[5] = byteCount; // 字节数

		// 填充数据
		for (let i = 0; i < quantity; i++) {
			pdu[6 + i * 2] = (values[i] >> 8) & 0xff; // 值高字节
			pdu[6 + i * 2 + 1] = values[i] & 0xff; // 值低字节
		}

		return pdu;
	}

	/**
	 * 解析读取位响应
	 * @param {Uint8Array} buffer 响应数据
	 * @returns {Object} 解析结果
	 */
	_parseReadBitsResponse(buffer) {
		const slaveId = buffer[0];
		const functionCode = buffer[1];
		const byteCount = buffer[2];

		// 检查数据长度
		if (buffer.length < 3 + byteCount + 2) {
			return {
				error: "数据长度不足"
			};
		}

		// 提取位值
		const values = [];
		for (let i = 0; i < byteCount; i++) {
			const byte = buffer[3 + i];
			for (let j = 0; j < 8; j++) {
				values.push((byte >> j) & 0x01 ? true : false);
			}
		}

		return {
			slaveId,
			functionCode,
			values,
		};
	}

	/**
	 * 解析读取寄存器响应
	 * @param {Uint8Array} buffer 响应数据
	 * @returns {Object} 解析结果
	 */
	_parseReadRegistersResponse(buffer) {
		const slaveId = buffer[0];
		const functionCode = buffer[1];
		const byteCount = buffer[2];

		// 检查数据长度
		if (buffer.length < 3 + byteCount + 2) {
			return {
				error: "数据长度不足"
			};
		}

		// 提取寄存器值
		const values = [];
		for (let i = 0; i < byteCount / 2; i++) {
			const high = buffer[3 + i * 2];
			const low = buffer[3 + i * 2 + 1];
			values.push((high << 8) | low);
		}

		return {
			slaveId,
			functionCode,
			values,
		};
	}

	/**
	 * 解析写单个线圈响应
	 * @param {Uint8Array} buffer 响应数据
	 * @returns {Object} 解析结果
	 */
	_parseWriteSingleCoilResponse(buffer) {
		const slaveId = buffer[0];
		const functionCode = buffer[1];
		const address = (buffer[2] << 8) | buffer[3];
		const value = buffer[4] === 0xff;

		return {
			slaveId,
			functionCode,
			address,
			value,
		};
	}

	/**
	 * 解析写单个寄存器响应
	 * @param {Uint8Array} buffer 响应数据
	 * @returns {Object} 解析结果
	 */
	_parseWriteSingleRegisterResponse(buffer) {
		const slaveId = buffer[0];
		const functionCode = buffer[1];
		const address = (buffer[2] << 8) | buffer[3];
		const value = (buffer[4] << 8) | buffer[5];

		return {
			slaveId,
			functionCode,
			address,
			value,
		};
	}

	/**
	 * 解析写多个响应
	 * @param {Uint8Array} buffer 响应数据
	 * @returns {Object} 解析结果
	 */
	_parseWriteMultipleResponse(buffer) {
		const slaveId = buffer[0];
		const functionCode = buffer[1];
		const address = (buffer[2] << 8) | buffer[3];
		const quantity = (buffer[4] << 8) | buffer[5];

		return {
			slaveId,
			functionCode,
			address,
			quantity,
		};
	}

	/**
	 * 计算CRC16校验
	 * @param {Uint8Array} buffer 数据
	 * @returns {number} CRC16校验值
	 */
	_calculateCRC16(buffer) {
		let crc = 0xffff;

		for (let i = 0; i < buffer.length; i++) {
			crc ^= buffer[i];

			for (let j = 0; j < 8; j++) {
				if (crc & 0x0001) {
					crc = (crc >> 1) ^ 0xa001;
				} else {
					crc = crc >> 1;
				}
			}
		}

		return crc;
	}

	/**
	 * 通知状态变化
	 * @param {Object} extraInfo 额外信息
	 */
	_notifyStateChange(extraInfo = null) {
		if (this.onStateChangeCallback) {
			this.onStateChangeCallback(this.state, extraInfo);
		}
	}

	/**
	 * 处理错误
	 * @param {string} message 错误信息
	 * @param {Object} error 错误对象
	 */
	_handleError(message, error) {
		const errorInfo = {
			message,
			error
		};
		console.error(errorInfo);
		if (this.onErrorCallback) {
			this.onErrorCallback(errorInfo);
		}
	}

	// 启动心跳保活
	_startHeartbeat() {
		// 先停止可能存在的心跳
		this._stopHeartbeat();

		// 如果心跳周期为0，表示禁用心跳
		if (this.heartbeatPeriod <= 0) {
			console.log("心跳保活已禁用");
			return;
		}

		// 启动新的心跳
		this.heartbeatInterval = setInterval(() => {
			// 只有在已连接状态才发送心跳
			if (this.state === BLUETOOTH_STATE.CONNECTED) {
				console.log("发送心跳包...");
				this._sendData(this.heartbeatData).catch((error) => {
					console.error("心跳包发送失败:", error);
					// 心跳失败可能意味着连接已断开，但系统尚未检测到
					// 主动检查连接状态
					this._checkConnectionStatus();
				});
			}
		}, this.heartbeatPeriod);

		console.log(`心跳保活已启动，周期: ${this.heartbeatPeriod}ms`);
	}

	// 停止心跳保活
	_stopHeartbeat() {
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval);
			this.heartbeatInterval = null;
		}
	}

	// 检查连接状态
	_checkConnectionStatus() {
		if (this.deviceId && this.state === BLUETOOTH_STATE.CONNECTED) {
			uni.getBLEDeviceServices({
				deviceId: this.deviceId,
				success: () => {
					// 连接正常
					console.log("连接状态检查：连接正常");
				},
				fail: () => {
					// 连接可能已断开，但系统未检测到
					console.log("连接状态检查：连接异常，尝试重连");
					// 手动触发重连
					this.state = BLUETOOTH_STATE.RECONNECTING;
					this._notifyStateChange();
					this.reconnectCount = 0;
					setTimeout(
						() => this.connect(this.deviceId, this.deviceName),
						this.reconnectDelay
					);
				},
			});
		}
	}
}

// 导出常量和类
export {
	BLUETOOTH_STATE,
	MODBUS_FUNCTION_CODE,
	BLUETOOTH_MODULE_TYPE,
	NORMAL_MODULE_UUID,
	BT16_MODULE_UUID,
	BluetoothModbus,
};